<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once ('base.php');

class Index extends Base {
	
	public function __construct()	{
		parent::__construct();
	}
	
	public function recentorder() {
		$this->load->library('session');
		if ($this->session->userdata('user') != null)	{
			$userId = $this->session->userdata('user')->id;
			$this->load->model('Order_model');
			$this->baseData['orders'] = $this->Order_model->listOrders($userId);
		} else {
			$this->baseData['orders'] = array();
		}
		$this->templateData['contentLeft'] = $this->load->view('orderlist',$this->baseData,true);
		$this->templateData['contentRight'] = '';
		$this->load->view('index', $this->templateData);
	}
	
	public function order($id)	{
		$this->load->model('Order_model');
		$order = $this->Order_model->getDetail($id);
		$order = $order[0];
		if ($order->status == 0)	{
			$order->status = "Đang chờ phê duyệt";
		} else if ($order->status == 1)	{
			$order->status = "Đã phê duyệt";
		}
		if ($order->payment == 1)	{
			$order->payment = "Trực tiếp";
		}
		if ($order->discount != 0 && $order->discount != null)
			$order->price = $order->discount;
		$this->baseData['order'] = $order;
		$this->templateData['contentLeft'] = $this->load->view('orderadmin',$this->baseData,true);
		$this->templateData['contentRight'] = '';
		$this->load->view('index', $this->templateData);
	}
	
	public function finalcheckout()	{
		$this->load->library('session');
		$userId = $this->session->userdata('user')->id;
		
		$address = $this->input->post('address');
		$phone = $this->input->post('phone');
		$this->load->model('User_model');
		$this->User_model->id = $userId;
		$this->User_model->editContactInfo($address, $phone);
		
		$this->load->model('Order_model');
		$payment = $this->input->post('payment');
		$orders = $this->Order_model->addPending($userId, $payment);
		
		$this->load->model('Product_model');
		$features = $this->Product_model->listFeaturedProducts();
		$this->templateData['contentLeft'] = $this->load->view('finalcheckout',$this->baseData,true);
		$this->load->view('index', $this->templateData);
	}
	
	public function cart()	{
		$this->load->model('Product_model');
		$features = $this->Product_model->listFeaturedProducts();
		$this->templateData['contentRight'] = $this->load->view('features', 
						array('BaseUrl'=>$this->baseData['BaseUrl'],'features'=>$features), true);
		
		$this->load->library('session');
		$sessionId = $this->session->userdata('session_id');
		$user = $this->session->userdata('user');
		if ($user != null)	{
			$userId = $user->id;
			
			$this->load->model('Order_model');
			$orders = $this->Order_model->getPending($userId);
			$total = 0;
			foreach($orders as $order)	{
				if ($order->discount != 0 && $order->discount != null)
					$total += $order->discount;
				else
					$total += $order->price;
			}
			$this->load->model('Product_model');
			$this->baseData = array(
				'BaseUrl' => $this->baseData['BaseUrl'],
				'orders' => $orders,
				'total' => $total,
				'address' => $user->address,
				'phone' => $user->phone
			);
		} else {
			$this->baseData = array(
				'BaseUrl' => $this->baseData['BaseUrl'],
				'orders' => array(),
				'total' => 0,
				'address' => "",
				'phone' => ""
			);
		}
		$this->templateData['contentLeft'] = $this->load->view('carts',$this->baseData,true);
		$this->load->view('index', $this->templateData);
	}
	
	public function index()
	{
		$this->load->model('Product_model');
		$features = $this->Product_model->listFeaturedProducts();
		$this->templateData['contentRight'] = $this->load->view('features', 
						array('BaseUrl'=>$this->baseData['BaseUrl'],'features'=>$features), true);
		
		$this->load->model('User_model');				
		$this->templateData['contentRight'] .= $this->load->view('recentusers', 
						array('BaseUrl'=>$this->baseData['BaseUrl'],'users'=>$this->User_model->listUsers(5)), true);
		
		$products = $this->Product_model->listFeaturedProducts();
		$this->loadProduct($products[0]->id);
		$featured = $this->load->view('productdetail',$this->baseData,true);
		$this->baseData = array(
			'BaseUrl' => $this->baseData['BaseUrl'],
			'title' => "Các sản phẩm mới cập nhật",
			'products' => $this->Product_model->listNewest(),
			'recentCheckedout' => $this->Product_model->listRecentCheckedout(),
			'featured'=>$featured
		);
		$this->templateData['contentLeft'] = $this->load->view('store',$this->baseData,true);
		$this->baseData = array(
			'BaseUrl' => $this->baseData['BaseUrl'],
			'title' => "Các sản phẩm từ Amazon",
			'products' => $this->Product_model->listByStore(1)
		);
		$this->templateData['contentLeft'] .= $this->load->view('other_stores',$this->baseData,true);
		$this->baseData = array(
			'BaseUrl' => $this->baseData['BaseUrl'],
			'title' => "Các sản phẩm từ Best Buy",
			'products' => $this->Product_model->listByStore(2)
		);
		$this->templateData['contentLeft'] .= $this->load->view('other_stores',$this->baseData,true);
		
		$this->load->view('index', $this->templateData);
	}
	
	public function search($keyword=""){
		$this->load->helper('url');
		if(empty($keyword))	{
			redirect('/');
			return;
		}
		$this->load->model('Service');
		$rs = $this->Service->search($keyword);
		
		$result = array();
		foreach($rs->Item as $item)	{
			$result[] = array('name'=>(string)$item->ItemAttributes->Title, 'id'=>(string)$item->ASIN, 'image'=>(string)$item->SmallImage->URL);
		}
		
		$this->baseData['products'] = $result;
		$this->baseData['resultCount'] = $rs->TotalResults;
		
		//display
		$this->load->model('Product_model');
		$features = $this->Product_model->listFeaturedProducts();
		$this->templateData['contentRight'] = $this->load->view('features', 
						array('BaseUrl'=>$this->baseData['BaseUrl'],'features'=>$features), true);
		$this->templateData['contentLeft'] = $this->load->view('search',$this->baseData,true);
		$this->load->view('index', $this->templateData);
	}
	
	public function checkprice($keyword="", $type=1)	{
		$this->load->helper('url');
		if(empty($keyword))	{
			redirect('/');
			return;
		}
		//find in db
		$this->load->model('Product_model');
		$this->baseData['similars'] = array();
		$result = $this->Product_model->search($keyword, $type);
		if ($result == null)	{
			//call webservice
			$this->load->model('Service');
			$result = $this->Service->lookup($keyword, $type);
			if ($result == null)
			{
				redirect('/');
				return;
			}
			if ($type == 1) {
				$discountPrice = 0;
				if (!is_null($result->Offers) && !is_null($result->Offers->Offer) && !is_null($result->Offers->Offer->OfferListing))	{
					$discountPrice = (int)$result->Offers->Offer->OfferListing->Price->Amount;
					if ($discountPrice < $result->ItemAttributes->ListPrice->Amount)
						$result->hasOffer = true;
					$result->discountPrice = $result->Offers->Offer->OfferListing->Price->FormattedPrice;
					$result->savedAmount = $result->Offers->Offer->OfferListing->AmountSaved->FormattedPrice;
					$result->savedPercentage = $result->Offers->Offer->OfferListing->PercentageSaved;
				}
				if (!is_null($result->ItemAttributes) && !is_null($result->ItemAttributes->ItemDimensions))	{
					$result->length = $result->ItemAttributes->ItemDimensions->Length;
					$result->width = $result->ItemAttributes->ItemDimensions->Width;
					$result->height = $result->ItemAttributes->ItemDimensions->Height;
					$result->weight = $result->ItemAttributes->ItemDimensions->Weight;
				}
				$length = strlen($result->DetailPageURL);
				if ($length > 40)	{
					$result->displayURL = substr($result->DetailPageURL, 0, 18)."...".substr($result->DetailPageURL, $length-19, 18);
				} else {
					$result->displayURL = $result->DetailPageURL;
				}
				
				//store in DB
				$this->Product_model->name = (string)$result->ItemAttributes->Title;
				$this->Product_model->price = $result->ItemAttributes->ListPrice->Amount/100;
				$this->Product_model->priceCurrency = (string)$result->ItemAttributes->ListPrice->CurrencyCode;
				$this->Product_model->discount = $discountPrice/100;
				if ($discountPrice  != 0)	{
					$this->Product_model->discountCurrency =  (string)$result->Offers->Offer->OfferListing->Price->CurrencyCode;
				}
				$this->Product_model->sku = (string)$result->ASIN;
				$this->Product_model->url = (string)$result->DetailPageURL;
				$this->Product_model->storeId = $type;
				$this->Product_model->image = (string)$result->LargeImage->URL;
				$this->Product_model->length = $result->length/100;
				$this->Product_model->width = $result->width/100;
				$this->Product_model->height = $result->height/100;
				$this->Product_model->weight = $result->weight/100;
				$pid = $this->Product_model->addNew();
				
				if ($result->SimilarProducts != null)	{
					$similarProducts = $result->SimilarProducts->SimilarProduct;
					foreach($similarProducts as $similar)	{
						$this->load->model('Similar_model');
						$this->Similar_model->addSimilar($pid, (string)$similar->ASIN, (string)$similar->Title);
					}
				}
				
				$this->Product_model->savedAmount = $result->savedAmount;
				$this->Product_model->savedPercentage = $result->savedPercentage;
				$this->Product_model->displayURL = $result->displayURL;
				$this->baseData['similars'] = $similarProducts;
			} else if ($type == 2)	{
				//store in DB
				$result = $result->product;
				$this->Product_model->name = (string)$result->name;
				$this->Product_model->price = (double)$result->regularPrice;
				$this->Product_model->priceCurrency = '$';
				$this->Product_model->discount = (double)$result->salePrice;
				$this->Product_model->discountCurrency = '$';
				$this->Product_model->sku = (string)$result->productId;
				$this->Product_model->url = (string)$result->url;
				$this->Product_model->storeId = (int)$type;
				$this->Product_model->image = (string)$result->largeImage;
				$this->Product_model->length = $this->normalizeBBMetric((string)$result->depth);
				$this->Product_model->width = $this->normalizeBBMetric((string)$result->width);
				$this->Product_model->height = $this->normalizeBBMetric((string)$result->height);
				$this->Product_model->weight = $this->normalizeBBMetric((string)$result->weight);
				$pid = $this->Product_model->addNew();
				
				$tag = (string)$result->categoryPath->category[1]->name;
				$this->load->model('Tag_model');
				$tagId = $this->Tag_model->getTagByContent($tag);
				$this->Tag_model->tagProduct($pid, $tagId);
				
				$this->Product_model->savedAmount = $result->planPrice;
				$this->Product_model->savedPercentage = $result->planPrice/$result->regularPrice;
				$this->Product_model->displayURL = $result->displayURL;
			}
			$this->baseData['result'] = $this->Product_model;
		} else {
			$length = strlen($result->url);
			if ($length > 40)	{
				$result->displayURL = substr($result->url, 0, 18)."...".substr($result->url, $length-19, 18);
			} else {
				$result->displayURL = $result->url;
			}
			
			$pid = $result->id;
			$this->load->model('Similar_model');
			$similarProducts = $this->Similar_model->getSimilars($pid);
			
			$result->savedAmount = $result->price-$result->discount;
			$result->savedPercentage = ceil($result->savedAmount*100/$result->price);
			$this->baseData['result'] = $result;
			$this->baseData['similars'] = $similarProducts;
		}
		
		//display
		$features = $this->Product_model->listFeaturedProducts();
		$this->templateData['contentRight'] = $this->load->view('features', 
						array('BaseUrl'=>$this->baseData['BaseUrl'],'features'=>$features), true);
		$this->templateData['contentLeft'] = $this->load->view('checkprice',$this->baseData,true);
		$this->load->view('index', $this->templateData);
	}

	private function normalizeBBMetric($metric) {
		if (empty($metric))
			return $metric;
		if (strpos($metric, ".") !== false)	{
			return (double)$metric;
		}
		$metrics = explode("-", $metric);
		$result = "";
		if (count($metrics) > 1)	{
			$result = $metrics[0];
			$metrics[0] = $metrics[1];
		}
		$metrics = explode("/",$metrics[0]);
		$result .= substr((double)$metrics[0] / (double)$metrics[1], 1);
		return (double)$result;
	}

	public function store($storeId=0,$page=0){
		$this->load->helper('url');
		if($storeId == 0) 
			redirect('/');
		$this->load->model('Store_model');
		$this->load->model('Product_model');
		$store = $this->Store_model->getById($storeId);
		$storeName = 'Không tìm thấy dữ liệu phù hợp.';
		$products = '';
		if(count($store)>0){
			$storeName = "Các sản phẩm từ ".$store[0]->name; 
			if($page == null || (int)$page < 0) $page = 0;
			$products = $this->Product_model->listByStore($storeId,$page);
		}
		$features = $this->Product_model->listFeaturedProducts(0, $storeId);
		if (!empty($features))	{
			$this->loadProduct($features[0]->id);
			$featured = $this->load->view('productdetail',$this->baseData,true);
		} else {
			$featured = "Chưa cập nhật";
		}
		$storeData = array(
			'BaseUrl' => $this->baseData['BaseUrl'],
			'title' => $storeName,
			'products' => $products,
			'recentCheckedout'=>null,
			'featured'=>$featured
		);
		$this->templateData['contentLeft'] = $this->load->view('store',$storeData,true);
		
		$features = $this->Product_model->listFeaturedProducts();
		$this->templateData['contentRight'] = $this->load->view('features', 
						array('BaseUrl'=>$this->baseData['BaseUrl'],'features'=>$features), true);
		$this->load->view('index', $this->templateData);
	}

	public function tag($tagId=0,$page=0){
		$this->load->helper('url');
		if($tagId == 0) redirect('/');
		$this->load->model('Product_model');
		$features = $this->Product_model->listFeaturedProducts();
		$this->templateData['contentRight'] = $this->load->view('features', 
						array('BaseUrl'=>$this->baseData['BaseUrl'],'features'=>$features), true);
		$this->load->model('Tag_model');
		$tag = $this->Tag_model->getTag($tagId);
		$tagName = 'Không tìm thấy dữ liệu phù hợp.';
		$products = '';
		if($tag != null){
			$tagName = "Các sản phẩm có tag ".$tag->content;
			$products = $this->Product_model->listByTag($tagId,$page);
		}
		$tagData = array(
			'BaseUrl' => $this->baseData['BaseUrl'],
			'title' => $tagName,
			'products' => $products,
			'featured' => null,
			'recentCheckedout' => null
		);
		$this->templateData['contentLeft'] = $this->load->view('store',$tagData,true);
		$this->load->view('index', $this->templateData);
	}
	
	public function loadProduct($productId)	{
		$this->load->helper('url');
		if($productId == 0) 
			redirect('/');
		$this->load->model('Product_model');
		$result = $this->Product_model->getById($productId);
		$similarProducts = array();
		if($result != null){
			$length = strlen($result->url);
			if ($length > 40)	{
				$result->displayURL = substr($result->url, 0, 18)."...".substr($result->url, $length-19, 18);
			} else {
				$result->displayURL = $result->url;
			}
			
			$result->savedAmount = $result->price-$result->discount;
			$result->savedPercentage = ceil($result->savedAmount*100/$result->price);
			
			$this->load->model('Similar_model');
			$similarProducts = $this->Similar_model->getSimilars($result->id);
		}
		
		$this->load->library('session');
		$user = $this->session->userdata('user');
		$liked = $checked = false;
		if ($user != null)	{
			$this->load->model('Like_model');
			$liked = $this->Like_model->hasLiked($user->id, $productId);
			
			$this->load->model('Order_model');
			$checked = $this->Order_model->hasCheckedOut($user->id, $productId);
		}
		
		$this->baseData['result'] = $result;
		$this->baseData['similars'] = $similarProducts;
		$this->baseData['liked'] = $liked;
		$this->baseData['checked'] = $checked;
		$this->baseData['productId'] = $productId;
	}

	public function product($productId=0){
		$this->loadProduct($productId);
		
		//display
		$features = $this->Product_model->listFeaturedProducts();
		$this->templateData['contentRight'] = $this->load->view('features', 
						array('BaseUrl'=>$this->baseData['BaseUrl'],'features'=>$features), true);
		$this->templateData['contentLeft'] = $this->load->view('productdetail',$this->baseData,true);
		$this->load->view('index', $this->templateData);
	}
	
	public function login()	{
		$submit = $this->input->post('submit');
		$error = "";
		if ($submit != null)	{
			$this->load->model('User_model');
			$this->User_model->email = $this->input->post('email', true);
			$this->User_model->password = $this->input->post('password', true);
			
			$result = $this->User_model->login();
			if ($result === null) {
				$error = "Sai email hoặc mật khẩu";
			} else {
				$this->load->library('session');
				$this->session->set_userdata('user', $result);
				$this->load->helper('url');
				redirect('/');
			}
		}
		
		//display
		$this->load->model('Product_model');
		$features = $this->Product_model->listFeaturedProducts();
		$this->templateData['contentRight'] = $this->load->view('features', 
						array('BaseUrl'=>$this->baseData['BaseUrl'],'features'=>$features), true);
		$this->baseData['error'] = $error;
		$this->templateData['contentLeft'] = $this->load->view('login',$this->baseData,true);
		$this->load->view('index', $this->templateData);
	}
	
	public function register()	{
		$submit = $this->input->post('submit');
		$error = "";
		if ($submit != null)	{
			$this->load->model('User_model');
			$this->User_model->email = $this->input->post('email', true);
			$this->User_model->password = $this->input->post('password', true);
			$this->User_model->name = $this->input->post('name', true);
			
			$result = $this->User_model->register();
			if ($result === null) {
				$error = "Không thể đăng ký. Bạn hãy thử lại sau";
			} else {
				$result = $this->User_model->getById($result);
				$this->load->library('session');
				$this->session->set_userdata('user', $result);
				$this->load->helper('url');
				redirect('/');
			}
		}
		
		//display
		$this->load->model('Product_model');
		$features = $this->Product_model->listFeaturedProducts();
		$this->templateData['contentRight'] = $this->load->view('features', 
						array('BaseUrl'=>$this->baseData['BaseUrl'],'features'=>$features), true);
		$this->baseData['error'] = $error;
		$this->templateData['contentLeft'] = $this->load->view('register',$this->baseData,true);
		$this->load->view('index', $this->templateData);
	}
	
	public function logout()	{
		$this->session->unset_userdata('user');
		$this->session->sess_destroy();
		$this->load->helper('url');
		redirect('/');
	}
	
	public function profile($userId=0){
		$this->load->helper('url');
		$user = $this->getUser();
		if($userId == 0) {
			if ($user == null)	{
				redirect('/');
			}
			$userId = $user->id;
		}
		$this->load->model('User_model');
		$result = $this->User_model->getPublicInfo($userId);
		if($result != null){
			$this->baseData['info'] = $result;
		}
		if ($user != null && $userId == $user->id)	{
			$this->baseData['currentUser'] = true;
		} else {
			$this->baseData['currentUser'] = false;
		}
		
		if ($user != null)	{
			$this->load->model('Follow_model');
			$this->baseData['isFollowing'] = $this->Follow_model->isUserFollowing($user->id, $userId);
		}
		
		//display
		$this->load->model('Product_model');
		$features = $this->Product_model->listFeaturedProducts();
		$this->templateData['contentRight'] = $this->load->view('features', 
						array('BaseUrl'=>$this->baseData['BaseUrl'],'features'=>$features), true);
		$this->templateData['contentLeft'] = $this->load->view('profile',$this->baseData,true);
		$this->load->view('index', $this->templateData);
	}

	public function followers($type=1,$objectId=0){
		$this->load->helper('url');
		if($type==1){
			$user = $this->getUser();
			if($objectId == 0) {
				if ($user == null)	{
					redirect('/');
				}
				$objectId = $user->id;
			}
			if ($user != null && $objectId == $user->id)	{
				$this->baseData['currentUser'] = true;
			} else {
				$this->baseData['currentUser'] = false;
			}
		
			if ($user != null)	{
				$this->load->model('Follow_model');
				$this->baseData['follows'] = $this->Follow_model->getFollowers($objectId);
			}
		}
		//display
		$this->load->model('Product_model');
		$features = $this->Product_model->listFeaturedProducts();
		$this->templateData['contentRight'] = $this->load->view('features', 
						array('BaseUrl'=>$this->baseData['BaseUrl'],'features'=>$features), true);
		$this->templateData['contentLeft'] = $this->load->view('follows',$this->baseData,true);
		$this->load->view('index', $this->templateData);
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */